package com.ck567.springbootnettyprotobufjava.server;

import com.ck567.springbootnettyprotobufjava.handler.MessageHandler;
import com.google.protobuf.MessageLite;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: MessageHandlerContainer Handler容器
 */
@Slf4j
@Component
public class MessageHandlerContainer implements InitializingBean {

    private final ApplicationContext context;

    private final Map<Short, MessageHandler<MessageLite>> handlers = new HashMap<>();

    @Autowired
    public MessageHandlerContainer(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        context.getBeansOfType(MessageHandler.class).values()
                .forEach(handler -> handlers.put(handler.getType(), handler));
        log.info("[MessageHandlerContainer] [Handler count]: {}", handlers.size());
    }


    /**
     * @param type 消息类型
     * @return 处理器
     * @description: 根据类型获取处理器
     * @author: YapuLv
     * @time: 2021/11/8 11:24
     */
    public MessageHandler<MessageLite> getHandler(short type) {
        MessageHandler<MessageLite> handler = handlers.get(type);
        if (handler == null) {
            throw new IllegalArgumentException(String.format("消息类型：%d，找不到匹配的处理器", type));
        }
        return handler;
    }
}
